import Addition from "@/components/Addition";
import QueryUserDefine from "@/components/QueryUserDefine";
import { s_getcommontableinfo, s_getTableInfo, s_operateInfo, s_updateInfo, state2text, status2text } from "@/services/basis";
import { ActionType, EditableFormInstance, EditableProTable, ProCard, ProColumns, ProForm, ProFormInstance, 
          ProFormRadio, ProFormSelect, ProFormText, ProFormTextArea, ProTable } from "@ant-design/pro-components"
import { Button, Col, message, Modal, Row, Space } from "antd";
import { useEffect, useRef, useState } from "react";
import { getSelection } from "@/services/selections";
import moment from "moment";
import QueryCustom from "@/components/QueryCustom";
import QueryMaterial2 from "@/components/QueryMaterial2";

const App:React.FC=()=>{
  const [open,setOpen]=useState(false);
  const [etype,setEtype]=useState(1);
  const [otype,setOtype]=useState(1);
  const [dataSource,setDataSource]=useState<DataType2[]>([]);
  const [selectedRecord,setSelectedRecord]=useState<DataType[]>([]);

  const [material,setMaterial]=useState<{id:any,code:any,name:any,invstd:any,invstd2:any,munit_name:any}[]>([]);
  const [custom,setCustom]=useState<{id:any,name:any,salecategory2:any}[]>([]);
  const [userdefine,setUserDefine]=useState<{uid:any,uname:any,vlabel:any,value:any}[]>([]);
  const [material_id,setMaterial_id]=useState(0);
  const [rowno,setRowno]=useState(0); 
  const [addition,setAddition]=useState([]);
  const [vouchCode,setVouchCode]=useState(null);

  const mtable_ref=useRef<ActionType>();
  const mform_ref=useRef<ProFormInstance>();
  const mtable2_ref=useRef<ActionType>();
  const editorFormRef=useRef<EditableFormInstance>();

  // id,x_id,code,org_id,purchase_type_id,custom_id,operater_id,
  // status,state,memo,source_queryprice_mid,dep_name,
  // purchasetype_name,custom_name,operater_name

  useEffect(()=>{
    if(custom.length>0){
      const v=custom[0];
      mform_ref.current?.setFieldsValue({
        custom_id:v.id,
        custom_name:v.name,
      });
    }
  },[custom]);

  useEffect(()=>{
    // if(userdefine.length>0){
      // alert(JSON.stringify(userdefine));
    const u=userdefine;
    var u1:any[]=[];
    var u2:any[]=[];
    u.map((item:any)=>{
      u1.push({uid:item.uid,value:item.value});
      u2.push(''.concat(item.uname,':',item.vlabel==''?item.value:item.vlabel));
    });

    editorFormRef.current?.setRowData?.(rowno.toString(),{
      userdefine_id:u1,
      userdefine_name:u2.toString(),
    });
     
  // }
  },[userdefine]);

  //当组件选择物料时，更新表格并重载--
        useEffect(()=>{
           if(material.length>0){
           var x:any[]=editorFormRef.current?.getRowsData?.();
           // alert(JSON.stringify(x));
           if(x==undefined)
              x=[];
           material.map((item:any)=>{
              x?.push({rid:Math.random().toFixed(10),id:Math.random().toFixed(10).toString(),
                        material_id:item.id,material_code:item.code,material_name:item.name,
                        invstd:item.invstd,invstd2:item.invstd2,munit_name:item.munit_name,  
                        hassample:0,deliverdate:moment().format('YYYY-MM-DD'),quantity:1, dosample:0,
                        userdefine_id:'[]',custom_id:'[]',
              });
           });
           // alert(JSON.stringify(x));
          setDataSource(x);
            
          mform_ref.current?.setFieldValue('editortable',x);
          mtable2_ref.current?.reloadAndRest?.();
        }
        },[material]);
  
  interface DataType{
      id:number,x_id:number,code:string,org_id:number,purchase_type_id:number,custom_id:number,operater_id:number,
      status:number,state:number,memo:string,source_queryprice_mid:number,dep_name:string,
      purchasetype_name:string,custom_name:string,operater_name:string,operate_time:string,addition:string,
   } 

   const columns:ProColumns<DataType>[]=[
    {dataIndex:'id',title:'id'},{dataIndex:'code',title:'销售单号'},{dataIndex:'addition',hidden:true},
    {dataIndex:'operate_time',title:'下单时间',valueType:'date'},{dataIndex:'custom_name',title:'客户'},
    {dataIndex:'dep_name',title:'部门'},{dataIndex:'purchasetype_name',title:'销售类型'},{dataIndex:'operater_name',title:'操作人'},
    {dataIndex:'state',title:'进度',
      render:(text:any)=>state2text(1,text),
    },
    {dataIndex:'status',title:'状态',
      render:(text:any)=>status2text(text),
    },
   ];

   interface DataType2{
    rid:number,id:number,mid:number,material_id:number,userdefine_id:string,userdefine_name:string,quantity:number,
    deliverdate:string,price:number,taxrate:number,total:number,netprice:number,tax:number,nettotal:number,
    memo:string,source_queryprice_id:number,
    material_code:string,material_name:string,invstd:string,invstd2:string,munit_name:string
   }

   const columns2:ProColumns<DataType2>[]=[
    {dataIndex:'rid',title:'rid',editable:false},{dataIndex:'id',title:'ID',editable:false},
    {dataIndex:'material_id',title:'物料ID'},
    {dataIndex:'userdefine_id',hidden:true},{dataIndex:'material_code',title:'物料编码',editable:false},
   {dataIndex:'material_name',title:'物料名称',editable:false},{dataIndex:'invstd',title:'规格',editable:false},
   {dataIndex:'invstd2',title:'型号',editable:false},
   {dataIndex:'userdefine_name',title:'属性',editable:false},
   {title:'属性',editable:false,
    render:(text,record)=><QueryUserDefine setData={setUserDefine} 
                  objtype={1} dotype={1} id={record.material_id} setRowno={setRowno} rowno={record.rid} />
   },
   {dataIndex:'munit_name',title:'主单位',editable:false},
   {dataIndex:'price',title:'含税单价',valueType:'digit',
    fieldProps:(_,{rowIndex})=>{
      return {
         onChange:()=>{
            // alert(rowIndex);
            const rowdata=editorFormRef?.current?.getRowData?.(rowIndex);
            // alert(JSON.stringify(rowdata));
            const quantity=rowdata?.quantity==null?0:rowdata?.quantity;
            const price=rowdata?.price==null?0:rowdata?.price;
            const taxrate=rowdata?.taxrate==null?0:rowdata?.taxrate;
            editorFormRef.current?.setRowData?.(rowIndex,
               {total:quantity*price,
                 netprice:price/(1+taxrate/100),
                 nettotal:(price/(1+taxrate/100))*quantity,
               });
         },
      }
   }
   },
   {dataIndex:'taxrate',title:'税率%',valueType:'digit',
    fieldProps:(_,{rowIndex})=>{
      return {
         onChange:()=>{
            // alert(rowIndex);
            const rowdata=editorFormRef?.current?.getRowData?.(rowIndex);
            // alert(JSON.stringify(rowdata));
            const quantity=rowdata?.quantity==null?0:rowdata?.quantity;
            const price=rowdata?.price==null?0:rowdata?.price;
            const taxrate=rowdata?.taxrate==null?0:rowdata?.taxrate;
            editorFormRef.current?.setRowData?.(rowIndex,
                {total:quantity*price,
                 netprice:price/(1+taxrate/100),
                 nettotal:(price/(1+taxrate/100))*quantity,
               });
         },
      }
   }
   },
   {dataIndex:'quantity',title:'数量',valueType:'digit',
    fieldProps:(_,{rowIndex})=>{
      return {
         onChange:()=>{
            // alert(rowIndex);
            const rowdata=editorFormRef?.current?.getRowData?.(rowIndex);
            // alert(JSON.stringify(rowdata));
            const quantity=rowdata?.quantity==null?0:rowdata?.quantity;
            const price=rowdata?.price==null?0:rowdata?.price;
            const taxrate=rowdata?.taxrate==null?0:rowdata?.taxrate;
            editorFormRef.current?.setRowData?.(rowIndex,
                {total:quantity*price,
                 netprice:price/(1+taxrate/100),
                 nettotal:(price/(1+taxrate/100))*quantity,
               });
         },
      }
   }
   },
   {dataIndex:'total',title:'价税合计',valueType:'digit',},
   {dataIndex:'deliverdate',title:'交付日期',valueType:'date',
      // render:(text:any)=>moment(moment(text).toDate()).format('YYYY-MM-DD'),
   },
   {dataIndex:'memo',title:'备注'},
   {
    title:'操作',
    fixed:'right',
    valueType:'option',
    width:80,
    render:(text,record,_,action)=>[
      //  <a key='edit2'
      //     onClick={()=>{
      //         alert(record.rid);
      //        action?.startEditable?.(record.rid);}}
      //  >
      //      编辑
      //  </a>,
       <a  key='del2'
           onClick={()=>{
             var x:any[]=editorFormRef.current?.getRowsData?.();
             //  alert(JSON.stringify(x));
             setDataSource(x.filter((item)=>item.id!=record.id));
             // alert(JSON.stringify(x.filter((item)=>item.id!=record.id)));
             // mtable2_ref.current?.reloadAndRest?.();
             mform_ref.current?.setFieldValue('editortable',x.filter((item)=>item.rid!=record.rid));
           }}
       >
           删除
       </a>,
    ]
 }
  ];
   function closeModal(){
      setOpen(false);
      setEtype(1);
      setVouchCode(null);
   }

   function add(){
    setEtype(1);
    setOpen(true);
   }

   async function edit(){
    if(selectedRecord.length==0)
      message.warning('请先选择要编辑的行');
    else{
        setEtype(0);
        // 获取对应的ID明细数据
        const x=await s_getcommontableinfo({x_id:1,source:'v_order_detail',id:0,fdata:{mid:selectedRecord[0].id}});
          alert(JSON.stringify(x.data[0]));
        if(x.data[0].length>0){
          setDataSource(x.data[0]);
          setVouchCode(selectedRecord[0].code);
          setOpen(true);
        }
    };
   }

  function saveModal(otype:number){
      mform_ref.current?.submit();
      const x=editorFormRef?.current?.getRowsData?.();
      x?.map((item,index)=>{
        mtable2_ref.current?.saveEditable?.(index);
      });

     setOtype(otype);
    //  setEtype(1);
    //  mform_ref.current?.submit();
   }

   async function saveModal2(){
        const fdata2=mform_ref.current?.getFieldsValue();
        const t1=fdata2.editortable;
        const t2=t1.map((item:any)=>({...item,deliverdate:moment(moment(item.deliverdate).toDate()).format('YYYY-MM-DD')}));
        const fdata={...fdata2,editortable:t2,addition};

         alert(JSON.stringify(fdata));
        // source,x_id,operater_id,etype,fdata
        const x=await s_updateInfo({x_id:2,source:'2purchase_order',operater_id:1,etype,fdata});
        if(x.success){
          message.success('保存成功');
          setEtype(1);
          setSelectedRecord([]);
          mtable_ref.current?.reloadAndRest?.();
          setOpen(false);
        }else
          message.error('保存失败，请联系管理员');

        

   }

   //  操作询价单/冻结/删除/恢复
   async function operateInfo(n:number){
    // source,x_id,operater_id,otype,id
    if(selectedRecord.length==0)
       message.warning('请选择要操作的行');
    else{
     const x=await s_operateInfo({x_id:2,source:'2order_main',operater_id:1,otype:n,id:selectedRecord[0].id});
     if(x.success){
       message.success('操作成功');
       mtable_ref.current?.reloadAndRest?.();
     }else
       message.error('操作错误，请联系管理员。');
    }
 }

  // 全部开始编辑，置表格为编辑状态
  function quote(){
    //用一个循环
    const x:any[]=editorFormRef.current?.getRowsData?.();
    if(x!=undefined&&x.length>0)
      x.map((item:any,index)=>{
          mtable2_ref.current?.startEditable?.(index);
       }
    );
    else
      message.warning('没有任何修改');
  }

  //获取价格
  async function getPrice(){
    const tdata=mform_ref.current?.getFieldValue('editortable');
    const ven_id=mform_ref.current?.getFieldValue('custom_id');
    if(tdata==undefined||ven_id==undefined||tdata.length==0||ven_id=='')
      message.warning('请先选择客户和物料明细');
    else{
      var x:any=[];
      x=await s_getcommontableinfo({source:'v_priceschedule2',x_id:1,id:0,fdata:{custom_id:ven_id}});
      alert(JSON.stringify(x));
      const tableData:any[]=editorFormRef?.current?.getRowsData?.();
      tableData.map((item:any,rowIndex:any)=>{
        const rowData=editorFormRef.current?.getRowData?.(rowIndex);
        x.data[0].map((item:any)=>{
            // 当前价格仅匹配客户+物料ID,后续应考虑自定义项
           if(rowData.material_id==item.material_id){
                editorFormRef.current?.setRowData?.(rowIndex,
                  {price:item.price,
                   taxrate:item.taxrate,
                   netprice:item.netprice,
                   total:rowData.quantity*item.price,
                   nettotal:rowData.quantity*item.netprice,
                   tax:rowData.qnantity*item.taxrate,
                  });  
           }
        });
      });
    }
  }

  //  主界面======================================================================================================
  return <>
     <ProCard title='销售订单管理'
       extra={<Space>
           {/* <Button onClick={()=>add()}>新增</Button> */}
           <Button onClick={()=>edit()}>查看</Button>
           <Button onClick={()=>operateInfo(13)}>接收</Button>
           <Button onClick={()=>operateInfo(14)}>拒绝接收</Button>
           <Button onClick={()=>operateInfo(18)}>取消接收</Button>
           {/* <Button onClick={()=>operateInfo(5)}>审核</Button>
           <Button onClick={()=>operateInfo(6)}>取消审核</Button> */}
           {/* <Button onClick={()=>operateInfo(2)}>冻结</Button>
           <Button onClick={()=>operateInfo(3)}>删除</Button>
           <Button onClick={()=>operateInfo(0)}>恢复</Button> */}
       </Space>}
     >
      {JSON.stringify(selectedRecord)}
      <ProTable<DataType>
        actionRef={mtable_ref}
        columns={columns}
        rowKey='id'
        request={async ()=>{
          // alert(11);
          const x=await s_getTableInfo({source:'v2_order_main',x_id:2,id:0});
          // alert(JSON.stringify(x.data));
          return {
            data:x.data,
            success:true,
          }
        }}
        rowSelection={{
          type:'radio',
          async onChange(selectedRowKeys, selectedRows, info) {
              setSelectedRecord(selectedRows);
             
          },
        }} 
         
      />
     </ProCard>

     {/* 订单编辑窗体----------------------------------------------------------------------------------------------------- */}
     <Modal open={open} closable destroyOnClose okButtonProps={{hidden:true}} cancelButtonProps={{hidden:true}}
        onCancel={()=>closeModal()} onClose={()=>closeModal()} width='80%'
     >
      <ProCard title='订单明细'
         extra={<Space>
          {/* <QueryMaterial2 setData={setMaterial} type='checkbox' x_id={1}/> */}
          {/* <Button onClick={()=>getPrice()}>获取价格</Button>
          <Button onClick={()=>quote()}>开始编辑</Button>
          <Button onClick={()=>saveModal(1)}>保存</Button>
          <Button onClick={()=>saveModal(2)}>保存并下达</Button> */}
          {/* <Button onClick={()=>operateInfo(12)}>下达</Button>
          <Button onClick={()=>operateInfo(19)}>取消下达</Button> */}
          <Button onClick={()=>closeModal()}>关闭</Button>
         </Space>}
      >
     {/* 表头 id,x_id,code,org_id,purchase_type_id,custom_id,operater_id,
     status,state,memo,source_queryprice_mid,dep_name,
     purchasetype_name,custom_name,operater_name */}
     {/* 表体 rid,id,mid,material_id,userdefine_id,userdefine_name,quantity,
     deliverdate,price,taxrate,total,netprice,tax,nettotal,memo,source_queryprice_id,
     material_code,material_name,invstd,invstd2,munit_name */}
       <ProForm submitter={false} formRef={mform_ref}
          onFinish={()=>saveModal2()}
          initialValues={etype==1?{
                       state:1,status:0,operater_id:1,
                     }:{
                       ...selectedRecord[0],
                       editortable:dataSource,
                     }}
       >
         <Row gutter={8}>
          <Col span={8}>
             <ProFormText name='code' label='单据编码' width={300}
               rules={[{required:true,message:'此为必填项'}]}
               fieldProps={{
               onChange:(e:any)=>{
                setVouchCode(e.target.value);
                // mform_ref.current?.setFieldValue('addition',e.target.value);
               }
               }}
             />
             <ProFormSelect name='org_id' label='部门' width={300}
             request={async ()=>{
              var x:any=await getSelection({ source: 'base_organization', x_id: 1 });
              var x2=x.data.map((item:any)=>({value:item.id,label:item.name}));
              return x2;
              }}
             />
             <ProFormSelect name='operater_id' label='操作人' width={300}
             rules={[{required:true,message:'此为必填项'}]}
              request={async ()=>{
                   var x:any=await getSelection({ source: 'base_person', x_id: 1 });
                   var x2=x.data.map((item:any)=>({value:item.id,label:item.name}));
                   return x2;
                   }}
             />
          </Col>
          <Col span={8}>
             <Space>
                  <ProFormText name='custom_name' label='客户' width={300}/>
                  <QueryCustom setData={setCustom} x_id={1} disabled={1} type='radio' />
             </Space>
             <ProFormSelect name='purchase_type_id' label='销售类型' width={300}
                request={async ()=>{
                  var x:any=await getSelection({ source: 'base_purchasetype', x_id: 1 });
                  var x2=x.data.map((item:any)=>({value:item.id,label:item.name}));
                  return x2;
                  }}
             />
             {/* {JSON.stringify(vouchCode)} */}
             <Addition source_xid={1} setData={setAddition} type={2}
                            fdata={{source_table:'addition_order_main',
                                  source_code:vouchCode,
                                  source_field:'addition',
                                  source_id:selectedRecord.length==0?0:selectedRecord[0].id,
                                  source_value:selectedRecord.length==0||selectedRecord[0].addition==null||selectedRecord[0].addition==''?[]:selectedRecord[0].addition}}
                         />
          </Col>
          <Col span={8}>
          <ProFormSelect name='state' label='进度' width={300} 
          rules={[{required:true,message:'此为必填项'}]}
          options={[{value:1,label:'未下达'},{value:2,label:'已下达'},{value:3,label:'供方已确认'},{value:4,label:'供方已拒绝'},
            {value:5,label:'已确认'},{value:6,label:'已拒绝'},{value:7,label:'撤销确认'},{value:8,label:'供方撤销确认'},
            {value:9,label:'撤销下达'},{value:10,label:'未提交'},{value:11,label:'已提交'},{value:12,label:'撤销提交'},
            {value:13,label:'已核价'},{value:14,label:'撤销核价'}
       ]}
          />
         <ProFormRadio.Group name='status' label='状态' width={300}
         rules={[{required:true,message:'此为必填项'}]}
              options={[{value:0,label:'未审核'},{value:2,label:'冻结'},
                      {value:5,label:'已审核'},{value:6,label:'弃审'},
                      {value:3,label:'删除'}]}
         />
          <ProFormTextArea name='memo' label='备注'  />
          </Col>
         </Row>
         <ProFormText name='id' label='ID' hidden/>
         <ProFormText name='custom_id' hidden />

         <EditableProTable<DataType2>
                               rowKey='rid'
                               name='editortable'
                              //  rowSelection={{
                              //    type:'checkbox',
                              //  }}
                               actionRef={mtable2_ref}
                               editableFormRef={editorFormRef}
                              //  value={dataSource}
                               onChange={(data:any)=>setDataSource(data)}
                               columns={columns2}
                              //  request={async ()=>{
                              //    return {
                              //       data:tdata2,
                              //       success:true,
                              //    }
                              //  }}
                               editable = {{                       // defaultDom = {save,cancel,delete} 可以酌情添加和使用
                                 actionRender: (row, config, defaultDom) => [
                                   defaultDom.save,
                                 //   defaultDom.cancel,
                                 ],
                                 type:'multiple'
                               }}
                               recordCreatorProps={false}
                            />
       </ProForm>
      </ProCard>
     
     </Modal>
  </>;
}

export default App;